package com.zx.idc.backend.gui.config.aspect;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.zx.idc.backend.gui.common.util.NetworkUtil;
import com.zx.idc.backend.gui.shiro.TokenManagerUtil;
import com.zx.idc.common.util.JsonUtil;
import com.zx.idc.ds.sys.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 全局 web 访问日志
 *
 * @author rxliuli
 * @date 2018/5/30
 */
@Component
public class WebLogInterceptor implements HandlerInterceptor {
    public static final String REQUEST_ID = "requestId";
    private final Logger log = LoggerFactory.getLogger(getClass());
    private Map<Long, WebLog> webLogMap = new ConcurrentHashMap<>();

    @Autowired
    private TokenManagerUtil tokenManagerUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        final long id = IdWorker.getId();
        CompletableFuture.runAsync(() -> {
            final SysUser sysUser = tokenManagerUtil.getCurrentUser();
            final WebLog webLog = new WebLog(NetworkUtil.getIpAddress(request), request.getRequestURI(), request.getParameterMap(), request.getMethod(), sysUser == null ? null : sysUser.getId());
            webLogMap.put(id, webLog);
        });
        request.setAttribute(REQUEST_ID, id);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        final long id = (long) request.getAttribute(REQUEST_ID);
        CompletableFuture.runAsync(() -> {
            final WebLog webLog = webLogMap.remove(id)
                .setStatus(response.getStatus());
            log.info("webLog: {}", JsonUtil.write(webLog));
            // TODO 此处或许应该保存到数据库
        });
    }
}